package com.ai_daily.aitiantian.api;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.sse.RealEventSource;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

public class StreamRequestTest2 {
    public static void main(String[] args) throws IOException {
        Gson gson = new Gson();
        MediaType mediaType = MediaType.parse("application/json");
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("androidId", "50306d21a7573e49");
        requestMap.put("question", "什么是精分人格？");
        RequestBody body = RequestBody.create(mediaType, gson.toJson(requestMap));
        Request request = new Request.Builder()
                .url("http://tiantianai.ai-daily.com.cn/aiChat/chat_v3")
                .post(body)
                .addHeader("Accept", "text/event-stream")
                .build();
        // 记录上一次接收消息的时间
        final long[] lastReceivedTime = {System.currentTimeMillis()};
        // 创建一个 CountDownLatch 对象，其初始计数为1，表示需要等待一个事件发生后才能继续执行。
        CountDownLatch eventLatch = new CountDownLatch(1);
        RealEventSource eventSource = new RealEventSource(request, new EventSourceListener() {
            @Override
            public void onFailure(@NonNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
                super.onFailure(eventSource, t, response);
                System.out.println("链接错误: " + eventSource);
            }

            @Override
            public void onOpen(@NonNull EventSource eventSource, @NonNull Response response) {
                super.onOpen(eventSource, response);
                System.out.println("链接打开: " + eventSource);
            }

            @Override
            public void onEvent(@NonNull EventSource eventSource, @Nullable String id, @Nullable String type, @NonNull String data) {
                super.onEvent(eventSource, id, type, data);
                System.out.println("接受消息: " + data);
                // 计算时间间隔
                long currentTime = System.currentTimeMillis();
                long interval = currentTime - lastReceivedTime[0];
                System.out.println("时间间隔--------" + interval + " ms");
                lastReceivedTime[0] = currentTime;
            }

            @Override
            public void onClosed(@NonNull EventSource eventSource) {
                super.onClosed(eventSource);
                System.out.println("链接断开: " + eventSource);
                // 计算时间间隔
                long currentTime = System.currentTimeMillis();
                long interval = currentTime - lastReceivedTime[0];
                System.out.println("时间间隔--------" + interval + " ms");
                lastReceivedTime[0] = currentTime;
            }
        });
        OkHttpClient okHttpClient = new OkHttpClient.Builder().callTimeout(600, TimeUnit.SECONDS).build();
        eventSource.connect(okHttpClient);
        try {
            eventLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
